const cloud = require('wx-server-sdk')

let db = cloud.database()
const _ = db.command
exports.main = async (event,context)=>{
	let start = event.start;
	let collectionName = event.collectionName;
	let result;
	let info = {};
	if(event.isVideo){
		info['is_video'] = 1
		if(event.user != 'roses_are_rosie'){
			info['user'] = event.user
		}else{
			info['user'] = _.exists(false)
		}
		result = await db.collection(collectionName).where(info).orderBy('taken_at_timestamp','desc')
		.limit(12).skip(start*12).get();
		
	}else{
		if(event.user != 'roses_are_rosie'){
			info['user'] = event.user
		}else{
			info['user'] = _.exists(false)
		}
		result = await db.collection(collectionName).where(info).orderBy('taken_at_timestamp','desc')
		.limit(12).skip(start*12).get();
	}
	let datas = result.data;
	let new_datas = datas.map(item=>{
		let conss;
		let tag_user;
		try{
			conss = item['edge_media_to_caption'];
			// Buffer.from(item['edge_media_to_tagged_user'], 'base64').toString().replace(/\u/g, "%u")).replace(/\\/g,"");
			tag_user = Buffer.from(item['edge_media_to_tagged_user'], 'base64').toString().replace(/\u/g, "%u").replace(/\\/g,"");
		}catch(e){
      item['errors'] = e
			// conss = item['edge_media_to_caption']
			tag_user = JSON.stringify([])
		}
		item['edge_media_to_caption'] = conss
		item['edge_media_to_tagged_user'] = tag_user
		return item
	})
	return {'msg':'ok','data':datas}
}